package com.fxy.demowebsockettest.server;

import com.fxy.demowebsockettest.pojo.utils.ConstUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/websocket")
public class MyWebSocket {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    // 基于场景考虑 这里使用线程安全的Map存储会话对象。
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();


    private Session _session;


    /**
     * @Description:建立连接
     * @Author: 范欣宜
     * @Date: 2020/12/1
     * @param session:
     * @return: void
     **/
    @OnOpen
    public void onOpen(Session session) {
        this._session = session;
        onlineSessions.put(session.getId(), session);

        try {
            sendMessageAll("欢迎来到知学聊天室");
        }catch (Exception e) {
            log.error("onOpen", e);
        }
        //在线客户总数
        log.info("有新用户加入，当前在线人数为" + onlineSessions.size()+"人");
    }

    /**
     * @Description:关闭一个连接
     * @Author: 范欣宜
     * @Date: 2020/12/1 8:16
     * @param session:
     * @return: void
     **/
    @OnClose
    public void onClose(Session session) {

        onlineSessions.remove(session.getId());
        //在线客户总数
        log.info("有一处连接关闭！当前在线人数为" + onlineSessions.size()+"人");
    }

    /**
     * @Description:接收消息
     * @Author: 范欣宜
     * @Date: 2020/12/1
     * @param message:
     * @param session:
     * @return: void
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        sendMessageAll(session.getId() + ":" + message);
        log.info("来自客户端的消息:" + message);
    }

    /**
     * @Description:发生错误
     * @Author: 范欣宜
     * @Date: 2020/12/1
     * @param session:
     * @param error:
     * @return: void
     **/
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
        rabbitTemplate.convertAndSend(ConstUtils.MQ_EXCHANGE_TOPIC_MSG_NAME, ConstUtils.MQ_QUEUE_TOPIC_MSG_NANE, message);
    }

    public void sendMessageAll(String message) {
        try {
            for(String key:onlineSessions.keySet()) {
                Session session = onlineSessions.get(key);
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
